<?php

namespace app\user\controller\tree\collect;

use app\BaseController;
use app\common\service\TreeSensitiveFilterService;
use app\model\tree\TreeCollectModel;
use app\model\tree\TreeFruitCommentModel;
use app\model\tree\TreeFruitImgModel;
use app\model\tree\TreeFruitLikeModel;
use app\model\tree\TreeFruitModel;
use app\model\tree\TreeUserInfoModel;
use app\model\UnitModel;
use think\App;

class Index extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 随机收取
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $TreeFruitModel = new TreeFruitModel();
            $info = $TreeFruitModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',1]
            ])->with([
                'user',
                'treeUserInfo',
                'fruitComment' => function ($query) {
                    $query->with(['user','treeUserInfo']);
                },
                'fruitImg'
            ])->orderRand()->find();
            if (!$info) throw new \Exception('还没有果实呢， 去投递果实吧！');
            $info = $info->toArray();
            if ($info['is_nickname']){
                $info['user_name'] = $info['nickname'];
                $info['avatar'] = $info['nickname_avatar'];
            }
            unset($info['nickname']);
            unset($info['nickname_avatar']);
            $TreeFruitLikeModel = new TreeFruitLikeModel();
            $isLike = $TreeFruitLikeModel->where([
                ['fruit_id','=',$info['id']],
                ['uid','=',$this->userData['id']]
            ])->find();
            if ($isLike){
                $info['is_like'] = 1;
            }else{
                $info['is_like'] = 0;
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 点赞
     * @return bool|string
     */
    public function like(): bool|string
    {
        $TreeFruitModel = new TreeFruitModel();
        $TreeFruitModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
                'status|状态' => 'require|in:0,1'
            ]);
            $info = $TreeFruitModel->find($param['id']);
            if (!$info) throw new \Exception('智慧果已被删除！');
            $TreeFruitLikeModel = new TreeFruitLikeModel();
            $isLike = $TreeFruitLikeModel->where([
                ['fruit_id','=',$param['id']],
                ['uid','=',$this->userData['id']]
            ])->find();
            if ($isLike){
                if ($param['status'] == 1) throw new \Exception('不可重复点赞！');
            }else{
                if ($param['status'] == 0) throw new \Exception('已取消！');
            }
            //是否有评论
            $TreeFruitCommentModel = new TreeFruitCommentModel();
            $log = $TreeFruitCommentModel->where([
                ['fruit_id','=',$param['id']],
                ['uid','=',$this->userData['id']]
            ])->find();
            if ($log){
                if ($isLike){
                    $info->dec('like_num')->save();
                    $isLike->save([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                }else{
                    $info->inc('like_num')->save();
                    $TreeFruitLikeModel->insert([
                        'fruit_id' => $param['id'],
                        'uid' => $this->userData['id'],
                        'time' => time()
                    ]);
                }
            }else{
                $TreeCollectModel = new TreeCollectModel();
                if ($isLike){
                    $TreeCollectModel->where([
                        ['fruit_id','=',$param['id']],
                        ['uid','=',$this->userData['id']]
                    ])->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    $info->dec('collect_num')->dec('like_num')->save();
                    $isLike->save([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                }else{
                    $TreeCollectModel->insert([
                        'fruit_id' => $param['id'],
                        'uid' => $this->userData['id'],
                        'time' => time()
                    ]);
                    $info->inc('collect_num')->inc('like_num')->save();
                    $TreeFruitLikeModel->insert([
                        'fruit_id' => $param['id'],
                        'uid' => $this->userData['id'],
                        'time' => time()
                    ]);
                }
            }
            $TreeFruitModel->commit();
            return success();
        } catch (\Exception $e) {
            $TreeFruitModel->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 评论
     * @return bool|string
     */
    public function comment(): bool|string
    {
        $TreeFruitCommentModel = new TreeFruitCommentModel();
        $TreeFruitCommentModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
                'content|评论内容' => 'require'
            ]);
            $log = $TreeFruitCommentModel->where([
                ['fruit_id','=',$param['id']],
                ['uid','=',$this->userData['id']]
            ])->find();
            if ($log) throw new \Exception('每颗果实只能参与一次评论！');
            $TreeFruitModel = new TreeFruitModel();
            $info = $TreeFruitModel->find($param['id']);
            if (!$info) throw new \Exception('智慧果已被删除！');
            if ($info['is_comment'] != 1) throw new \Exception('该果实未开启评论功能！');
            //处理内容（剔除敏感词）
            $UnitModel = new UnitModel();
            $tree_sensitive = $UnitModel->where('id','=',$this->userData['unit_id'])->value('tree_sensitive');
            if ($tree_sensitive == 1) {
                $TreeSensitiveFilterService = new TreeSensitiveFilterService($this->app);
                $param['content'] = $TreeSensitiveFilterService->filter($this->userData['unit_id'], $param['content']);
                $TreeSensitiveFilterService->updateLexicon($this->userData['unit_id'], $TreeSensitiveFilterService->wordsData);
            }
            $info->inc('collect_num')->save();
            $TreeFruitCommentModel->insert([
                'fruit_id' => $param['id'],
                'uid' => $this->userData['id'],
                'content' => $param['content'],
                'time' => time()
            ]);
            $TreeCollectModel = new TreeCollectModel();
            $isCollect = $TreeCollectModel->where([
                ['fruit_id','=',$param['id']],
                ['uid','=',$this->userData['id']]
            ])->value('id');
            if (!$isCollect){
                $TreeCollectModel->insert([
                    'fruit_id' => $param['id'],
                    'uid' => $this->userData['id'],
                    'time' => time()
                ]);
            }
            $TreeFruitCommentModel->commit();
            return success();
        } catch (\Exception $e) {
            $TreeFruitCommentModel->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 智慧果添加
     * @return bool|string
     */
    public function add(): bool|string
    {
        $TreeFruitModel = new TreeFruitModel();
        $TreeFruitModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'content|内容' => 'require',
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            if (!empty($param['img']) || !empty($param['file'])){
                $param['is_file'] = 1;
            }
            if (!empty($param['img'])){
                $imgData = [];
                foreach ($param['img'] as $img){
                    $imgData[] = [
                        'img' => $img,
                        'time' => $param['time']
                    ];
                }
                unset($param['img']);
            }
            if (!isset($param['is_nickname']) || strlen($param['is_nickname']) == 0){
                //获取用户配置
                $TreeUserInfoModel = new TreeUserInfoModel();
                $userInfo = $TreeUserInfoModel->where('uid','=',$this->userData['id'])->find();
                if ($userInfo['send_is_nickname']??0){
                    $param['is_nickname'] = 1;
                }
            }
            //处理内容（剔除敏感词）
            $UnitModel = new UnitModel();
            $tree_sensitive = $UnitModel->where('id','=',$this->userData['unit_id'])->value('tree_sensitive');
            if ($tree_sensitive == 1) {
                $TreeSensitiveFilterService = new TreeSensitiveFilterService($this->app);
                $param['content'] = $TreeSensitiveFilterService->filter($this->userData['unit_id'], $param['content']);
                $TreeSensitiveFilterService->updateLexicon($this->userData['unit_id'], $TreeSensitiveFilterService->wordsData);
            }
            //添加智慧果
            $fruit_id = $TreeFruitModel->insertGetId($param);
            if (!empty($imgData)){
                foreach ($imgData as &$v){
                    $v['fruit_id'] = $fruit_id;
                }
                $TreeFruitImgModel = new TreeFruitImgModel();
                $TreeFruitImgModel->insertAll($imgData);
            }
            $TreeFruitModel->commit();
            return success();
        } catch (\Exception $e) {
            $TreeFruitModel->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}